/*******************************************************************************
 * Dreampalace
 *******************************************************************************
 * 
 * Dreampalace is a special dreamdiary which helps dreamers to understand their
 * dreams. You can find also many features in Dreampalace to learn and hold the
 * lucid state in your dreams.
 * 
 * *****************************************************************************
 *
 * Program	   : Dreampalace
 * Autor           : PRo (Peter Rogge)
 * Email           : rogge-peter@gmx.de
 * Homepage        : http://code.google.com/p/dreampalace
 * License	   : GNU General Public License 3.0
 * 
 *******************************************************************************
 * 
 * This file is part of the project Dreampalace. Dreampalace is free software:
 * you can redistribute it and/or modify it under the terms of the GNU General 
 * Public License as published by the Free Software Foundation in version 3 of
 * the License only.
 * 
 * Dreampalace is distributed in the hope that it will be useful, but WITHOUT 
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * Dreampalace. If not, see <http://www.gnu.org/licenses/>.
 * 
 * The Dreampalace project designates this particular file as subject to the
 * "Classpath" exception as provided by the Dreampalace project in the GPL 
 * Version 3 section of the License file that accompanied this code.
 * 
 *******************************************************************************
 */
package de.pro.dreampalace.file.notes;

import com.zenjava.jfxflow.actvity.AbstractActivity;
import com.zenjava.jfxflow.navigation.NavigationManager;
import de.pro.dreampalace.file.api.EFileTyp;
import de.pro.dreampalace.util.api.IUtilManager;
import java.sql.*;
import java.util.logging.Logger;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.scene.input.KeyEvent;
import javafx.scene.web.HTMLEditor;
import org.openide.util.Lookup;
import org.openide.util.NbBundle;

/**
 * 
 * @author Peter Rogge (PRo) <rogge-peter@gmx.de>
 */
public final class NotesEditorActivity extends AbstractActivity {
    
    private boolean isDirty = Boolean.FALSE;
    
    private Connection connection = null;
    
    @FXML private HTMLEditor htmlEditor = null;
    private NavigationManager navigationManager = null;
    
    @Override
    protected final void activated() {
        System.out.println("NotesActivity.activated()");
        isDirty = Boolean.FALSE;
        
        htmlEditor.setHtmlText(this.loadFileNotes());
        htmlEditor.setOnKeyPressed(new EventHandler<KeyEvent>() {

            @Override
            public void handle(KeyEvent arg0) {
                if (!isDirty) {
                    isDirty = Boolean.TRUE;
                }
            }
        });
    }
    
    private String loadFileNotes() {
        final ResultSet result = this.loadFileNotesFromDatabase();
        String notes = null;
        try {
            result.next();
            
            final IUtilManager um = Lookup.getDefault().lookup(IUtilManager.class);
            notes = um.getTextFromClob(result.getClob(1));
        } catch (SQLException ex) {
            notes = NbBundle.getMessage(this.getClass(), "notes.initial"); // NOI18N
            this.saveNewFileNotes(notes);
        } finally {
            if (result != null) {
                try {
                    result.close();
                } catch (SQLException ex) { }
            }
        }
        
        return notes;
    }
    
    private ResultSet loadFileNotesFromDatabase() {
        PreparedStatement ps = null;
        ResultSet result = null;
        
        try {
            ps = connection.prepareStatement(
                    "SELECT Content " // NOI18N
                    + "FROM File " // NOI18N
                    + "WHERE ID=?"); // NOI18N
            ps.setLong(1, EFileTyp.NOTES_EDITOR.getID());
            
            result = ps.executeQuery();
        } catch (SQLException ex) {
            return null;
        } finally {
            if (ps != null) {
                try {
                    ps.close();
                } catch (SQLException ex) { }
            }
        }

        return result;
    }

    @Override
    protected void deactivated() {
        // No need of saving
        System.out.println("NotesActivity.deactivated()");
        if (!isDirty) { return; }
        
        // Content is changed so save it
        this.updateFileNotes();
    }
    
    private void saveNewFileNotes(final String notes) {
        Logger.getLogger(NotesEditorActivity.class.getName()).info(
                "Save file NOTES first time :)"); // NOI18N
        
        PreparedStatement ps = null;
        
        try {
            ps = connection.prepareStatement(
                    "INSERT INTO File(" // NOI18N
                        + "ID, Title," // NOI18N
                        + "Date, Content, " // NOI18N
                        + "FileTyp" + ") " // NOI18N
                    + "VALUES(?, ?, ?, ?, ?)"); // NOI18N

            ps.setLong(1, EFileTyp.NOTES_EDITOR.getID());
            ps.setString(2, "Notes"); // NOI18N
            ps.setDate(3, new java.sql.Date(System.currentTimeMillis()));
            ps.setClob(4, this.getClob(notes));
            ps.setString(5, EFileTyp.NOTES_EDITOR.toString());

            ps.execute();
        } catch (SQLException ex) {
            Logger.getLogger(NotesEditorActivity.class.getName()).warning(
                "Can't insert the file NOTES:"); // NOI18N
            Logger.getLogger(NotesEditorActivity.class.getName()).warning(
                ex.getMessage());
        } finally {
            try {
                if(ps != null) { ps.close(); }
            } catch (SQLException ex) { }
        }
    }
    
    private void updateFileNotes() {
        Logger.getLogger(NotesEditorActivity.class.getName()).info(
                "File NOTES is changed --> so save it"); // NOI18N
        
        PreparedStatement ps = null;
        
        try {
            ps = connection.prepareStatement(
                    "UPDATE File " // NOI18N
                    + "SET Content=? " // NOI18N
                    + "WHERE ID=?"); // NOI18N

            ps.setClob(1, this.getClob(htmlEditor.getHtmlText()));
            ps.setLong(2, EFileTyp.NOTES_EDITOR.getID());

            ps.execute();
        } catch (SQLException ex) {
            Logger.getLogger(NotesEditorActivity.class.getName()).warning(
                "Can't update the file NOTES:"); // NOI18N
            Logger.getLogger(NotesEditorActivity.class.getName()).warning(
                ex.getMessage());
        } finally {
            try {
                if(ps != null) { ps.close(); }
            } catch (SQLException ex) { }
        }
    }
    
    private Clob getClob(final String text) throws SQLException {
        final Clob clob = connection.createClob();
        clob.setString(1, text);

        return clob;
    }
    
    public final void onActionClearText(final ActionEvent event) {
        System.out.println("onActionClearText(ActionEvent)");
        isDirty = Boolean.TRUE;
        
        htmlEditor.setHtmlText(NbBundle.getMessage(this.getClass(), "notes.empty")); // NOI18N
        htmlEditor.requestFocus();
    }
    
    public final void onActionInitialText(final ActionEvent event) {
        System.out.println("onActionInitialText(ActionEvent)");
        isDirty = Boolean.TRUE;
        
        htmlEditor.setHtmlText(NbBundle.getMessage(this.getClass(), "notes.initial")); // NOI18N
        htmlEditor.requestFocus();
    }
    
    public final void onActionGoToPlaceHome(final ActionEvent event) {
        System.out.println("onActionGoToPlaceHome(ActionEvent)");
//        navigationManager.
    }
    
    public final void setConnection(final Connection connection) {
        this.connection = connection;
    }

    public final void setNavigationManager(final NavigationManager navigationManager) {
        this.navigationManager = navigationManager;
    }
}
